package com.google.coffeeshop.gui.desktop.statistics;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Vector;

import javax.persistence.EntityManager;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;

import net.sf.dynamicreports.jasper.builder.JasperReportBuilder;
import net.sf.dynamicreports.report.exception.DRException;

import com.google.coffeeshop.business.AbstractBaseBusiness;
import com.google.coffeeshop.business.StatisticsBusiness;
import com.google.coffeeshop.entity.EmployeeDTO;
import com.google.coffeeshop.entity.ProductDTO;
import com.google.coffeeshop.gui.desktop.ContentBasePanel;
import com.google.coffeeshop.gui.desktop.DatePicker;
import com.google.coffeeshop.gui.desktop.ObservingTextField;
import com.jgoodies.forms.factories.FormFactory;
import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.RowSpec;

import javax.swing.JButton;

import vn.bang.utility.DateUtil;

import java.awt.event.ActionListener;
import java.awt.Font;

public class StatisticsPanel extends ContentBasePanel {
	private static final long serialVersionUID = 1L;
	public static int action = 1;
	private ObservingTextField txtDate;
	private ObservingTextField txtFrom;
	private ObservingTextField txtTo;
	private JComboBox<ProductDTO> cbbProduct;
	private JComboBox<EmployeeDTO> cbbEmployee;
	public StatisticsPanel(String constraints) {
		super(constraints);
		init();
	}
		public void init(){
			setLayout(new FormLayout(new ColumnSpec[] {
					FormFactory.RELATED_GAP_COLSPEC,
					ColumnSpec.decode("max(147dlu;default)"),
					FormFactory.RELATED_GAP_COLSPEC,
					ColumnSpec.decode("max(205dlu;default)"),
					FormFactory.RELATED_GAP_COLSPEC,
					FormFactory.BUTTON_COLSPEC,},
				new RowSpec[] {
					FormFactory.RELATED_GAP_ROWSPEC,
					FormFactory.DEFAULT_ROWSPEC,
					FormFactory.RELATED_GAP_ROWSPEC,
					FormFactory.DEFAULT_ROWSPEC,
					FormFactory.RELATED_GAP_ROWSPEC,
					FormFactory.DEFAULT_ROWSPEC,
					FormFactory.RELATED_GAP_ROWSPEC,
					FormFactory.DEFAULT_ROWSPEC,
					FormFactory.RELATED_GAP_ROWSPEC,
					FormFactory.DEFAULT_ROWSPEC,
					FormFactory.RELATED_GAP_ROWSPEC,
					FormFactory.DEFAULT_ROWSPEC,}));
			
				JLabel lblProduct = new JLabel("Product");
				add(lblProduct, "2, 6, right, default");
				// add comboBox + mapping Entity
				final	EntityManager entityManager = AbstractBaseBusiness.createEntityManager();
				List<ProductDTO> activeProducts = new ArrayList<ProductDTO>(); 
				activeProducts = StatisticsBusiness.getAllActiveProducts(entityManager);
				final Vector<ProductDTO> listProductAsVector = new Vector<ProductDTO>();
				
				if(null != activeProducts && !activeProducts.isEmpty()) {
						for(ProductDTO product : activeProducts)
							listProductAsVector.add(product);
					final DefaultComboBoxModel<ProductDTO> model = new DefaultComboBoxModel<ProductDTO>(listProductAsVector);
				    cbbProduct = new JComboBox<ProductDTO>(model);
				}
				else cbbProduct = new JComboBox<>();
				add(cbbProduct, "4, 6, fill, default");
			
			JButton btnStatistics = new JButton("Statistic");
			add(btnStatistics, "4, 12, center, top");
			cbbProduct.setSelectedItem(null);
			cbbProduct.setRenderer(new DefaultListCellRenderer() {
				private static final long serialVersionUID = 1L;

				@Override
		           public Component getListCellRendererComponent(
		                   JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
		               super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
		               if (value instanceof ProductDTO) {
		            	   ProductDTO mec = (ProductDTO)value;
		                   setText(mec.getCode() + " " + mec.getName());
		               }
		               return this;
		           }
		       });
		if(action==1) {
			JLabel lblTitle = new JLabel("INVENTORY");
			lblTitle.setFont(new Font("Adobe Caslon Pro Bold", Font.PLAIN, 20));
			add(lblTitle, "4, 2, center, default");
			
			JLabel lblDate = new JLabel("Date");
			add(lblDate, "2, 8, right, default");
			
			txtDate = new ObservingTextField();
			add(txtDate, "4, 8");
			txtDate.setColumns(10);
			txtDate.setEditable(false);
			txtDate.setText(DateUtil.toString(DateUtil.getNow()));
			
			JButton btnDatePicker = new JButton("...");
			btnDatePicker.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					datePicker(txtDate);
				}
			});
			add(btnDatePicker, "6, 8, left, default");
			btnStatistics.addMouseListener(new MouseAdapter() {
				@Override
				public void mouseClicked(MouseEvent arg0) {
					
					InventoryDesign design = new InventoryDesign();
					ProductDTO product = (ProductDTO) cbbProduct.getSelectedItem();
					if(null!= product)
						design.productId= product.getId();	
					design.date= DateUtil.toDate(txtDate.getText());
					
					try {		
						JasperReportBuilder report = design.build();
						report.show(false);
					} catch (DRException e) {
						e.printStackTrace();
					}
					catch(NullPointerException e){
						JOptionPane.showMessageDialog(null,"No products!","INFORMATION",JOptionPane.WARNING_MESSAGE);
					}
				
				}
			});
			
		}
		// add label, datePicker
		else {
			JLabel lblFrom = new JLabel("From Date");
			add(lblFrom, "2, 8, right, default");
			
			txtFrom = new ObservingTextField();
			add(txtFrom, "4, 8");
			txtFrom.setColumns(10);
			txtFrom.setEditable(false);
			
			JButton btnDatePickerFrom = new JButton("...");
			btnDatePickerFrom.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					datePicker(txtFrom);
				}
			});
			add(btnDatePickerFrom, "6, 8, left, default");
			
			JLabel lblTo = new JLabel("To Date");
			add(lblTo, "2, 10, right, top");
			
			txtTo = new ObservingTextField();
			add(txtTo, "4, 10");
			txtTo.setColumns(10);
			txtTo.setEditable(false);
			txtTo.setText(DateUtil.toString(DateUtil.getNow()));
			
			JButton btnDatePickerTo = new JButton("...");
			btnDatePickerTo.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					datePicker(txtTo);
				}
			});
			add(btnDatePickerTo, "6, 10, left, default");
			// Import, add event for button Statistics
			if(action==2){
				JLabel lblTitle = new JLabel("IMPORT PRODUCT");
				lblTitle.setFont(new Font("Adobe Caslon Pro Bold", Font.PLAIN, 20));
				add(lblTitle, "4, 2, center, default");
				btnStatistics.addMouseListener(new MouseAdapter() {
					@Override
					public void mouseClicked(MouseEvent arg0) {
						ImportDesign design = new ImportDesign();
						ProductDTO product = (ProductDTO) cbbProduct.getSelectedItem();
						if(null!= product)
							design.productId= product.getId();
						design.beginDate= DateUtil.toDate(txtFrom.getText());
						design.endDate= DateUtil.toDate(txtTo.getText());
						
						try {						
							JasperReportBuilder report = design.build();
							report.show(false);
						} catch (DRException e) {
							e.printStackTrace();
						}
						catch(NullPointerException e){
							JOptionPane.showMessageDialog(null,"No products imported!","INFORMATION",JOptionPane.WARNING_MESSAGE);
						}
					}
				});
			}
			// Export, add event for button Statistics
			else if (action==3){
				JLabel lblTitle = new JLabel("EXPORT PRODUCT");
				lblTitle.setFont(new Font("Adobe Caslon Pro Bold", Font.PLAIN, 20));
				add(lblTitle, "4, 2, center, default");				btnStatistics.addMouseListener(new MouseAdapter() {
					@Override
					public void mouseClicked(MouseEvent arg0) {						
						ExportDesign design = new ExportDesign();
						ProductDTO product = (ProductDTO) cbbProduct.getSelectedItem();
						if(null!= product)
							design.productId= product.getId();
						design.beginDate= DateUtil.toDate(txtFrom.getText());
						design.endDate= DateUtil.toDate(txtTo.getText());
						
						try {													
							JasperReportBuilder report = design.build();
							report.show(false);
						} catch (DRException e) {
							e.printStackTrace();
						}
						catch(NullPointerException e){
							JOptionPane.showMessageDialog(null,"No products exported!","INFORMATION",JOptionPane.WARNING_MESSAGE);
						}
					}
				});
			}
			// Sale & Income, add event for button Statistics
			else {
				JLabel lblTitle = new JLabel("SALE & INCOME");
				lblTitle.setFont(new Font("Adobe Caslon Pro Bold", Font.PLAIN, 20));
				add(lblTitle, "4, 2, center, default");
				JLabel lblEmployee = new JLabel("Employee");
				add(lblEmployee, "2, 4, right, default");
				// add comboBox + mapping Entity
				List<EmployeeDTO> employees = new ArrayList<EmployeeDTO>(); 
				employees = StatisticsBusiness.getAllEmployees(entityManager);
				final Vector<EmployeeDTO> listEmployeeAsVector = new Vector<EmployeeDTO>();
				
				if(null != employees && !employees.isEmpty()) {
						for(EmployeeDTO employee : employees)
							listEmployeeAsVector.add(employee);
					final DefaultComboBoxModel<EmployeeDTO> model = new DefaultComboBoxModel<EmployeeDTO>(listEmployeeAsVector);
				    cbbEmployee = new JComboBox<EmployeeDTO>(model);
				}
				else cbbEmployee = new JComboBox<>();
				add(cbbEmployee, "4, 4, fill, default");
			
			cbbEmployee.setSelectedItem(null);
			cbbEmployee.setRenderer(new DefaultListCellRenderer() {
				private static final long serialVersionUID = 1L;

				@Override
		           public Component getListCellRendererComponent(
		                   JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
		               super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
		               if (value instanceof EmployeeDTO) {
		            	   EmployeeDTO mec = (EmployeeDTO)value;
		                   setText(mec.getCode() + " " + mec.getFullName());
		               }
		               return this;
		           }
		       });

				btnStatistics.addMouseListener(new MouseAdapter() {
					@Override
					public void mouseClicked(MouseEvent arg0) {					
						SaleIncomeDesign design = new SaleIncomeDesign();
						design.beginDate= DateUtil.toDate(txtFrom.getText());
						design.endDate= DateUtil.toDate(txtTo.getText());	
						if(cbbEmployee.getSelectedItem() != null)
							design.employee = (EmployeeDTO)cbbEmployee.getSelectedItem();
						if(cbbProduct.getSelectedItem()!=null)
							design.product = (ProductDTO)cbbProduct.getSelectedItem();
						try {											
							JasperReportBuilder report = design.build();
							report.show(false);
						} catch (DRException e) {
							e.printStackTrace();
						}
						catch(NullPointerException e){
							
						}
					
					}
				});
			}
			
		}
	}
		public void refreshGUI(){
			removeAll();
			init();
			validate();
			repaint();
		}
		private Locale getLocale(String loc){
			if(loc != null && loc.length()>0)
				return new Locale(loc);
			else
				return Locale.FRANCE;
		}
		private void datePicker(ObservingTextField txtDate){
			String lang =null;
			final Locale locale = getLocale(lang);
			DatePicker dp = new DatePicker(txtDate, locale);
			Date selectedDate = dp.parseDate(txtDate.getText());
			dp.setSelectedDate(selectedDate);
			dp.start(txtDate);
		}
}